<template>
	<!-- SKU弹窗组件 -->
	<vk-data-goods-sku-popup v-model="isShowSku" :localdata="供选单项" :mode="mode" add-cart-background-color="#FFA868"
		buy-now-background-color="#27BA9B" ref="skuPopupRef" :actived-style="{
      color: '#27BA9B',
      borderColor: '#27BA9B',
      backgroundColor: '#E9F8F5',
    }" @add-cart="onAddCart" @buy-now="onBuyNow" borderRadius="20" />
	<scroll-view enable-back-to-top scroll-y class="viewport">
		<!-- 基本信息 -->
		<view class="goods">
			<!-- 商品主图 -->
			<view class="preview">
				<swiper @change="onChange" circular autoplay>
					<swiper-item v-for="(item,index) in 单项?.图片组" :key="item">
						<image class="image" @tap="预览图片(item,单项?.图片组)" mode="aspectFill" :src="item" />
					</swiper-item>
				</swiper>
				<view class="indicator">
					<text class="current">{{ currentIndex + 1 }}</text>
					<text class="split">/</text>
					<text class="total">{{ 单项?.图片组?.length }}</text>
				</view>
			</view>

			<!-- 商品简介 -->
			<view class="bg-primary">
				<view class="q-pa-sm row justify-between">
					<view class="row a-zzi">
						<text class="">{{ 单项.名称 }}</text>
					</view>
					<view class="row a-dazi">
						<view class="text-orange rmb">
							{{显示价格}}
						</view>
					</view>
				</view>
			</view>

			<!-- 操作面板 -->
			<view class="action">
				<view @tap="openSkuPopup(SkuMode.Both)" class="item arrow">
					<text class="label">可选配置</text>
					<text class="text ellipsis"> {{ selectArrText }} </text>
				</view>
				<!-- 				<view @tap="openPopup('address')" class="item arrow">
					<text class="label">送至</text>
					<text class="text ellipsis"> 请选择收获地址 </text>
				</view>
				<view @tap="openPopup('service')" class="item arrow">
					<text class="label">服务</text>
					<text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
				</view> -->
			</view>
		</view>

		<!-- 商品详情 -->
		<view class="detail panel">
			<view class="title">
				<text>详情</text>
			</view>
			<view class="content">
				<view class="properties">
					<!-- 属性详情 -->
					<view class="item" v-for="item in 单项?.属性" :key="item.名称">
						<text class="label">{{ item.名称 }}</text>
						<text class="value">{{ item.内容 }}</text>
					</view>
				</view>
				<!-- 单项.详情:{{单项.详情}} -->
				<view class="q-px-sm">
					<rich-text :nodes="单项.详情" v-if="单项.详情" :preview="true"></rich-text>
				</view>
			</view>
		</view>

	</scroll-view>

	<!-- 用户操作 -->
	<view v-if="单项" class="toolbar" :style="{ paddingBottom: 安全区距底 + 'px' }">
		<view class="icons">
			<button class="icons-button" @click="点收藏"><text class="icon-heart"></text>收藏</button>
			<!-- #ifdef MP-WEIXIN -->
			<button class="icons-button" open-type="contact">
				<text class="icon-handset"></text>客服
			</button>
			<!-- #endif -->
			<button class="icons-button" @tap="去购物车"><text class="icon-cart"></text>购物车</button>
			<!-- 			<navigator class="icons-button" url="/pages/cart/cart2" open-type="navigate">
				<text class="icon-cart"></text>购物车
			</navigator> -->
		</view>
		<view class="buttons">
			<view @tap="onAddCart(SkuMode.Cart)" class="addcart"> 加入购物车 </view>
			<view @tap="onBuyNow(SkuMode.Buy)" class="payment"> 立即购买 </view>
		</view>
	</view>


</template>
<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { watchEffect, reactive, computed, ref } from 'vue'

	import * as util from '@/amtf/utils'
	import { 安全区距底 } from '@/amtf/utils/system';

	import { 查商品, } from '@/api/api'

	import { myRouter } from '@/utils/permission';

	import use_user from "@/stores/use_user";

	import { formatTimeToStr } from "@/utils/date.js"

	const 单项 = reactive({})
	const collectionFlag = ref('')
	const id = ref(0)
	const user = use_user()

	const 初始化 = async () => {
		const res = await 查商品({
			id: id.value
		})
		console.log('res.data', res.data);
		// res.code === 0 ? 单项.value = res.data : ''
		util.对象重予(单项, res.data)
		单项.图片组 = 单项.图片组.map(item => {
			// console.log('处理路径后图片组item: ', item);
			return util.予图片路径(item)
		})
		单项.详情 = util.图片元素加后台(单项.详情)
	}

	const 供选单项 = computed(() => {
		// console.log('sku 计算中: ');
		if (Object.keys(单项).length == 0) {
			return {}
		}
		// console.log('sku 计算中 有值: ');
		let obj = {
			_id: 单项.id,
			name: 单项.名称,
			goods_thumb: util.予图片路径(单项.图片组[0]),
			spec_list: 可选配置重组(),
			sku_list: 单项.skus.map((v) => {
				return {
					_id: v.id,
					goods_id: 单项.id,
					goods_name: 单项.名称,
					image: util.予图片路径(v.图片),
					price: v.价格 * 100, // 注意：需要乘以 100
					stock: v.库存,
					sku_name_arr: v.可选配置值?.map((vv) => vv.value),
				}
			})
		}
		console.log('obj: ', obj);
		return obj
	})

	const 可选配置重组 = () => {
		const specs = 单项.可选配置
		const skus = 单项.skus
		let obj = {}
		skus.map((sku) => {
			let 可选配置值 = sku.可选配置值
			// console.log('可选配置值: ', 可选配置值);
			可选配置值?.map((item) => {
				if (!obj[item.label]) {
					obj[item.label] = {}
				}
				obj[item.label][item.value] = ""
			})
		})

		let arr = Object.keys(obj).map((key) => {
			let obj1 = {}
			obj1.name = key
			let 值对象 = obj[key]
			obj1.list = Object.keys(值对象).map((k) => {
				return {
					name: k,
				}
			})
			return obj1
		})
		// console.log('arr: ', arr);
		return arr
	}

	// 接收页面参数，不接收会报错！
	const props = defineProps({
		id: {
			type: String,
			default: ''
		}
	})

	onLoad(async (options) => {
		if (options.id) {
			id.value = options.id
			await 初始化()
		}
	})
	// 轮播图变化时
	const currentIndex = ref(0)
	const onChange = (ev) => {
		currentIndex.value = ev.detail.current
	}
	import { storeToRefs } from 'pinia'
	import use购物车 from "@/stores/use购物车.js"
	// console.log('onChange: ');
	// const 购物车 = use购物车(false)

	// const 处理路径后图片组 = computed(() => {
	// 	// console.log('处理路径后图片组:单项 ', 单项);
	// 	let arr = 单项?.图片组?.map(item => {
	// 		// console.log('处理路径后图片组item: ', item);
	// 		return util.予图片路径(item)
	// 	})
	// 	// console.log('arr: ', arr);
	// 	return arr
	// })

	watchEffect(() => {
		// if (!单项.详情) return
		// 单项.详情 = 单项.详情.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
		// 	console.log('capture: ', capture);
		// 	const 新 = util.予图片路径(capture)
		// 	// console.log('新: ', 新);
		// 	return match.replace(capture, 新);
		// });

	})

	const 点收藏 = () => {
		uni.showToast({
			title: '这个还没搞好😄',
		})
	}

	const 去购物车 = () => {
		if (!user.要登录否()) return
		uni.navigateTo({
			url: '/pages/cart/cart2'
		})
	}

	const 预览图片 = (current, urls) => {
		// 大图预览
		// console.log('大图预览 图片路径处理.处理后图片组.value: ', 图片路径处理.处理后图片组);
		// console.log('大图预览 图片路径处理.处理后图片组: ', 图片路径处理.处理后图片组.value[index]);
		// console.log('index: ', index);
		// 不能接受 hooks传递过来的 computted!!!因为不是响应式的，图片路径处理变化后，不能同步变化？
		uni.previewImage({
			current,
			urls,
		})
	}

	// uni-ui 弹出层组件 ref
	const popup = ref({
		open: (type) => {},
		close: () => {}
	});

	// 弹出层条件渲染
	const popupName = ref(null);
	const openPopup = (name) => {
		// 修改弹出层名称
		popupName.value = name;
		popup.value?.open();
	};

	// 是否显示SKU组件
	const isShowSku = ref(false);

	// 按钮模式
	const SkuMode = {
		Both: 1,
		Cart: 2,
		Buy: 3
	};
	const mode = ref(SkuMode.Cart);
	// 打开SKU弹窗修改按钮模式
	const openSkuPopup = (val) => {
		// 显示SKU弹窗
		isShowSku.value = true;
		// 修改按钮模式
		mode.value = val;
	};

	// SKU组件实例
	const skuPopupRef = ref(null);
	// 计算被选中的值
	const selectArrText = computed(() => {
		return skuPopupRef.value?.selectArr?.join(' ').trim() || '请选择商品配置';
	});

	const 显示价格 = computed(() => {
		return skuPopupRef.value?.priceCom || 单项.价格;
	});

	function 选好配置否(params) {
		if (!params._id) {
			let res = skuPopupRef.value.checkSelectComplete()
			console.log('checkSelectComplete res: ', res);
			if (!res) {
				openSkuPopup(params)
				return false
			}
		}
		return true
	}

	// 加入购物车事件
	const onAddCart = async (ev) => {
		console.log('onAddCart ev: ', ev);
		if (!user.要登录否()) return
		// console.log('ev._id: ', ev._id);
		// 直接点击当前页面按钮触发，判断是否要弹窗sku
		if (!选好配置否(ev)) return
		// sku组件触发
		// await postMemberCartAPI({
		// 	skuId: ev._id,
		// 	count: ev.buy_num
		// });
		const 购物车 = use购物车()
		购物车.增或改({
			商品id: ev.goods_id,
			skuid: ev._id,
			数量: ev.buy_num
		})
		uni.showToast({
			title: '添加成功'
		});
		isShowSku.value = false;
	};

	// 立即购买
	const onBuyNow = (ev) => {
		if (!user.要登录否()) return
		if (!选好配置否(ev)) return
		const sku = util.查元素(单项.skus, ev._id)
		const 购物车 = use购物车()
		Object.assign(购物车.直接下单项, {
			商品id: ev.goods_id,
			商品: 单项,
			skuid: ev._id,
			sku,
			数量: ev.buy_num
		})
		uni.navigateTo({
			url: `/pagesOrder/create/create?zhijiemai=0`
		});
	};
</script>
<style lang="scss" scoped>
	.viewport {
		background-color: #f4f4f4;
		padding-bottom: 100rpx;
	}

	.panel {
		margin-top: 20rpx;
		background-color: #fff;

		.title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 90rpx;
			line-height: 1;
			padding: 30rpx 60rpx 30rpx 6rpx;
			position: relative;

			text {
				padding-left: 10rpx;
				font-size: 28rpx;
				color: #333;
				font-weight: 600;
				border-left: 4rpx solid #27ba9b;
			}

			navigator {
				font-size: 24rpx;
				color: #666;
			}
		}
	}

	.arrow {
		&::after {
			position: absolute;
			top: 50%;
			right: 30rpx;
			content: '\e6c2';
			color: #ccc;
			font-family: 'erabbit' !important;
			font-size: 32rpx;
			transform: translateY(-50%);
		}
	}

	/* 商品信息 */
	.goods {
		background-color: #fff;

		.preview {
			height: 750rpx;
			position: relative;

			.image {
				width: 750rpx;
				height: 750rpx;
			}

			.indicator {
				height: 40rpx;
				padding: 0 24rpx;
				line-height: 40rpx;
				border-radius: 30rpx;
				color: #fff;
				font-family: Arial, Helvetica, sans-serif;
				background-color: rgba(0, 0, 0, 0.3);
				position: absolute;
				bottom: 30rpx;
				right: 30rpx;

				.current {
					font-size: 26rpx;
				}

				.split {
					font-size: 24rpx;
					margin: 0 1rpx 0 2rpx;
				}

				.total {
					font-size: 24rpx;
				}
			}
		}

		.meta {
			position: relative;
			border-bottom: 1rpx solid #eaeaea;

			.price {
				height: 130rpx;
				padding: 25rpx 30rpx 0;
				color: #fff;
				font-size: 34rpx;
				box-sizing: border-box;
				background-color: #35c8a9;
			}

			.number {
				font-size: 56rpx;
			}

			.brand {
				width: 160rpx;
				height: 80rpx;
				overflow: hidden;
				position: absolute;
				top: 26rpx;
				right: 30rpx;
			}

			.name {
				max-height: 88rpx;
				line-height: 1.4;
				margin: 20rpx;
				font-size: 32rpx;
				color: #333;
			}

			.desc {
				line-height: 1;
				padding: 0 20rpx 30rpx;
				font-size: 24rpx;
				color: #cf4444;
			}
		}

		.action {
			padding-left: 20rpx;

			.item {
				height: 90rpx;
				padding-right: 60rpx;
				border-bottom: 1rpx solid #eaeaea;
				font-size: 26rpx;
				color: #333;
				position: relative;
				display: flex;
				align-items: center;

				&:last-child {
					border-bottom: 0 none;
				}
			}

			.label {
				width: 110rpx;
				color: #898b94;
				margin: 0 16rpx 0 10rpx;
			}

			.text {
				flex: 1;
				-webkit-line-clamp: 1;
			}
		}
	}

	/* 商品详情 */
	.detail {
		padding-left: 20rpx;

		.content {
			margin-left: -20rpx;

			.image {
				width: 100%;
			}
		}

		.properties {
			padding: 0 20rpx;
			margin-bottom: 30rpx;

			.item {
				display: flex;
				line-height: 2;
				padding: 10rpx;
				font-size: 26rpx;
				color: #333;
				border-bottom: 1rpx dashed #ccc;
			}

			.label {
				width: 200rpx;
			}

			.value {
				flex: 1;
			}
		}
	}

	/* 同类推荐 */
	.similar {
		.content {
			padding: 0 20rpx 20rpx;
			background-color: #f4f4f4;
			display: flex;
			flex-wrap: wrap;

			.goods {
				width: 340rpx;
				padding: 24rpx 20rpx 20rpx;
				margin: 20rpx 7rpx;
				border-radius: 10rpx;
				background-color: #fff;
			}

			.image {
				width: 300rpx;
				height: 260rpx;
			}

			.name {
				height: 80rpx;
				margin: 10rpx 0;
				font-size: 26rpx;
				color: #262626;
			}

			.price {
				line-height: 1;
				font-size: 20rpx;
				color: #cf4444;
			}

			.number {
				font-size: 26rpx;
				margin-left: 2rpx;
			}
		}

		navigator {
			&:nth-child(even) {
				margin-right: 0;
			}
		}
	}

	/* 底部工具栏 */
	.toolbar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: calc((var(--window-bottom)));
		z-index: 1;
		background-color: #fff;
		height: 100rpx;
		padding: 0 20rpx;
		border-top: 1rpx solid #eaeaea;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-sizing: content-box;

		.buttons {
			display: flex;

			&>view {
				width: 220rpx;
				text-align: center;
				line-height: 72rpx;
				font-size: 26rpx;
				color: #fff;
				border-radius: 72rpx;
			}

			.addcart {
				background-color: #ffa868;
			}

			.payment {
				background-color: #27ba9b;
				margin-left: 20rpx;
			}
		}

		.icons {
			padding-right: 20rpx;
			display: flex;
			align-items: center;
			flex: 1;

			// 兼容 H5 端和 App 端的导航链接样式
			.navigator-wrap,
			.icons-button {
				flex: 1;
				text-align: center;
				line-height: 1.4;
				padding: 0;
				margin: 0;
				border-radius: 0;
				font-size: 20rpx;
				color: #333;
				background-color: #fff;

				&::after {
					border: none;
				}
			}

			text {
				display: block;
				font-size: 34rpx;
			}
		}
	}
</style>